package com.gt.quality.system.service.impl;

import cn.idev.excel.EasyExcel;
import cn.idev.excel.FastExcel;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.quality.base.BusinessSelfException;
import com.gt.quality.config.SpringBeanUtil;
import com.gt.quality.config.utils.UserStatus;
import com.gt.quality.system.entity.SysFileInfo;
import com.gt.quality.system.entity.SysUser;
import com.gt.quality.system.entity.dto.SysUserDTO;
import com.gt.quality.system.entity.vo.QueryWhereUser;
import com.gt.quality.system.mapper.SysUserMapper;
import com.gt.quality.base.pojo.BaseLimitRequest;
import com.gt.quality.system.service.SysFileInfoService;
import com.gt.quality.system.service.SysUserService;
import com.gt.quality.system.service.excel.BaseExcelInputListener;
import com.gt.quality.system.service.excel.SysUserExcelInputListener;
import com.gt.quality.system.service.excel.user.ExcelExportUserInfo;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * 用户信息表(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2026-11-25 16:30:08
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysFileInfoService sysFileInfoService;


    /**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: makeJava
     * @date: 2026-02-02 14:57:06
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    @Override
    public IPage<SysUser> queryLimitPage(BaseLimitRequest<SysUser> limitRequest) {
        SysUser requestBody = limitRequest.getRequestBody();
        IPage<SysUser> page = getByPageParam(limitRequest);
        JSONObject thisObj = JSONObject.from(requestBody);
        QueryWrapper<SysUser> queryWrapper = queryWrapperBuilder(thisObj, limitRequest);
        return sysUserMapper.selectPage(page, queryWrapper);
    }


    /**
     * Description:  批量新增优化版
     *
     * @param entityList entityList
     * @author: makeJava
     * @date: 2026-02-02 19:54:59
     */
    @Override
    public Integer saveBatchByEasyBaseMapper(List<SysUser> entityList) {

        return sysUserMapper.insertBatchSomeColumn(entityList);
    }

    @Override
    public SysUser findUserByNameAndPassword(String loginAccount, String password) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", loginAccount);
        queryWrapper.eq("password", password);
        queryWrapper.eq("status", UserStatus.OK.getCode());
        return sysUserMapper.selectOne(queryWrapper);
    }

    /**
     * Description: 分页多表联查
     *
     * @param limitRequest limitRequest
     * @author: makeJava
     * @date: 2026-12-22 19:49:36
     */
    @Override
    public IPage<SysUserDTO> queryLimit(QueryWhereUser limitRequest) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(limitRequest.getUserName());
        sysUser.setSex(limitRequest.getDbSex());
        sysUser.setNickName(limitRequest.getNickName());
        sysUser.setDeptId(limitRequest.getDeptId());
        IPage<SysUserDTO> page = new Page<>(limitRequest.getPageIndex(), limitRequest.getPageSize());
        List<SysUserDTO> listResult = sysUserMapper.listQueryForWhereParam(page, sysUser);
        page.setRecords(listResult);
        return page;
    }


    /**
     * 上传文件方法
     * 该方法用于处理文件上传，特别是用于导入Excel文件中的用户数据到系统中
     * 它首先检查文件是否为空，然后使用EasyExcel库读取Excel文件中的数据
     * 如果文件为空，则抛出IllegalArgumentException异常；如果文件读取过程中发生错误，则抛出自定义的BusinessSelfException异常
     *
     * @param file 用户上传的文件，类型为MultipartFile，代表上传的文件对象
     */
    @Override
    public SysFileInfo uploadFile(MultipartFile file) {
        // 检查上传的文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        // EasyExcel 读取Excel文件里的内容到List
        try (InputStream inputStream = file.getInputStream()) {
            // 使用EasyExcelFactory读取输入流中的数据，映射到SysUser类，并使用SysUserExcelInputListener监听并处理读取到的数据
            EasyExcel.read(inputStream, ExcelExportUserInfo.class, new SysUserExcelInputListener(sysUserMapper)).sheet().doRead();
        } catch (Exception e) {
            // 记录错误日志，并抛出自定义异常，指示用户导入失败
            log.error("用户导入失败", e);
            throw new BusinessSelfException("用户导入失败,请联系管理员");
        }
        // 保存文件信息
        return sysFileInfoService.saveFileInfo(file);
    }

    /**
     * Description: 通用的excel导入示例
     *
     * @author: makeJava
     * @date: 2025-01-05 11:35:11
     */
    @SuppressWarnings("unused")
    public SysFileInfo uploadExcel(MultipartFile excel) {
        // 检查上传的文件是否为空
        if (excel.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        // EasyExcel 读取Excel文件里的内容到List
        try (InputStream inputStream = excel.getInputStream()) {
            BaseMapper<SysUser> mapper = sysUserMapper;
            BaseExcelInputListener<SysUser> listener = new BaseExcelInputListener<>(mapper);
            // 使用EasyExcelFactory读取输入流中的数据，映射到SysUser类，并使用SysUserExcelInputListener监听并处理读取到的数据
            FastExcel.read(inputStream, SysUser.class, listener).sheet().doRead();
        } catch (Exception e) {
            // 记录错误日志，并抛出自定义异常，指示用户导入失败
            log.error("用户导入失败", e);
            throw new BusinessSelfException("用户导入失败,请联系管理员");
        }
        // 保存文件信息
        return sysFileInfoService.saveFileInfo(excel);
    }


    /**
     * 往上传递 SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    @Override
    public SqlSessionFactory getSqlSessionFactory() {
        return super.getSqlSessionFactory();
    }

    /**
     * 往上传递 Mapper
     *
     * @return Mapper
     */
    @Override
    public Class<?> getThisMapperClass() {
        return SysUserMapper.class;
    }

    /**
     * 往上传递 Transaction
     *
     * @return Transaction
     */
    @Override
    public TransactionTemplate getSpringTx() {
        return SpringBeanUtil.getBean(TransactionTemplate.class);
    }
}


